
package maquinavotar.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.swing.JPanel;

public class HistoryManager {
    
    private ArrayList<ArrayList<JPanel>> history = null;
    
    public HistoryManager() {
        history = new ArrayList<ArrayList<JPanel>>();
    }
    
    public void updateHistory(ArrayList<JPanel> radioPanels) {
        ArrayList<JPanel> clonedList = new ArrayList<JPanel>(radioPanels.size());
        for(JPanel item : radioPanels) {
            clonedList.add( cloneJPanel(item) );
        }
        history.add(clonedList);
    }
    
    public ArrayList<JPanel> loadHistory(JPanel panel, ArrayList<JPanel> radioPanels) {
        if(history.size() > 1) {
            history.remove(history.size()-1); // Remove screen current
            
            for(JPanel radioPanel : radioPanels) // Remove panels RadioButton of layout
                panel.remove(radioPanel);
            
            return history.get(history.size()-1); // Update panels RadioButton
        }
        return null;
    }
    
    private JPanel cloneJPanel(JPanel orig) {
        try {
            // Put the object into a ByteArrayOutputStream
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(orig);
            // ByteArrayInputStream build in order to read it
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            return (JPanel) ois.readObject();
        } catch(Exception eio){}
        return null;
    }   
    
    public boolean existHistory() {
        return history.size() > 1;
    }
    
}
